﻿using UnityEngine;
using System.Collections;

// 캐스터 계열 캐릭터가 cast 이벤트에서 날리는 발사체 //
public class BProjectile : MonoBehaviour {

	bool bMoveComplete;
	public GameObject hitFXPrefab;
	PawnManifest parent;
	PawnManifest target;
	public ProjectileInfo info;

	static float supportGuardTime = 0.3f;

	public float MoveToTarget(PawnManifest _parent , PawnManifest _target, Vector3 targetPos)
	{
		parent = _parent;
		target = _target;
		bMoveComplete=false;
		float dist = (targetPos - transform.position).magnitude;
		if(info.speed==0)
			info.speed=10;
		float duration = dist/info.speed;
		StartCoroutine("CoStartSupportDefense"  ,duration - supportGuardTime);

//		Debug.Log ("== projectile MoveToTarget  dist="+dist+"   speed="+info.speed+"    time="+duration);
		Hashtable tweenOption = new Hashtable();
		tweenOption.Add("ease", info.tweenType);
		tweenOption.Add("onComplete", "MoveComplete");
		tweenOption.Add("onCompleteTarget", this.gameObject);
		if(info.curveUpOffset==0)
			LeanTween.move(gameObject, targetPos, duration, tweenOption);
		else {
			Vector3 midUp = (transform.position + targetPos)/2 + Vector3.up * info.curveUpOffset;
			Vector3 [] pos = { transform.position, midUp,midUp, targetPos };
			LeanTween.move(gameObject, pos, duration, tweenOption);
		}
		return duration;
	}

	IEnumerator CoStartSupportDefense(float delay)
	{
		if(delay>0)
			yield return new WaitForSeconds(delay);
		parent.CheckSupportDef();
	}

	void MoveComplete()
	{
		if(bMoveComplete)
			return;
		bMoveComplete=true;

//		Debug.Log("projectile MoveComplete");
		GetComponentInChildren<ParticleSystem>().Stop ();
		GetComponentInChildren<ParticleSystem>().loop = false;
		if(hitFXPrefab!=null) {
			GameObject go = Instantiate(hitFXPrefab) as GameObject;
			go.transform.parent = transform;
			BattleUtil.ClearTransformLocal(go.transform);
			go.SetActive(true);
			Destroy(go,2.0f);
		}
		//parent.parentPawn.isProjectileCasting=false;
		parent.projectile = null;
		parent.FirstHit();
		target.OnDamageByProjectile(parent.damageToTarget, 0.1f);
		Invoke ("TurnEnd", 0.2f);
		if(target.parentPawn.isDead)
			parent.parentPawn.CancelSupportAttack();
		else
			Invoke("CheckSupportAtk",0.2f);
		Destroy(gameObject,3.0f);
	}

	void TurnEnd()
	{
		parent.parentPawn.bTurnEnd=true;
	}

	void CheckSupportAtk()
	{
		parent.CheckSupportAttack();
	}

}
